﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class bestellen_Default : System.Web.UI.Page
{
    MovieManager mm;
    TicketManager tm;
    PlanningManager pm;
    ReservationManager rm;
    DateTimeConverter dtc = new DateTimeConverter();

    film currentMovie;
    planning currentPlanning;
    bestelling currentOrder;
    account currentAccount;

    string language = "dutch";
    int movieID;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Master.getUser() == null)
        {
            Response.Redirect("~/Login.aspx?redirect=bestellen/default.aspx" + (!String.IsNullOrEmpty(Request.QueryString["id"]) ? "?id=" + int.Parse(Request.QueryString["id"]) : ""));
        }

        mm = new MovieManager((debioscoopEntities)Session["db"]);
        rm = new ReservationManager((debioscoopEntities)Session["db"]);
        tm = new TicketManager((debioscoopEntities)Session["db"]);
        pm = new PlanningManager((debioscoopEntities)Session["db"]);

        language = Master.tl.getCurrentLanguage();
        currentAccount = Master.getUser();

        if (Session["planning"] != null || !String.IsNullOrEmpty(Request.QueryString["id"]))
        {
            if (Session["planning"] != null)
            {
                currentPlanning = (planning)Session["planning"];
                currentMovie = currentPlanning.film;
            }
            else
            {
                movieID = int.Parse(Request.QueryString["id"]);
                currentMovie = mm.getMovie(movieID);
            }

            if (!IsPostBack)
            {
                //Fill controls with info from the film object
                movieImg.ImageUrl = currentMovie.url;
                movTitle.Text = currentMovie.naam;
                movGenres.Text = mm.getGenreInString(currentMovie, ",", Master.tl.getCurrentLanguage());
                movLength.Text = currentMovie.duur.ToString();
                movProducer.Text = currentMovie.reggiseur;
                availableTickets.Visible = false;

                ddlPlanning.DataSource = dtc.getDatesFromNow(language);
                ddlPlanning.DataTextField = "value";
                ddlPlanning.DataValueField = "key";
                ddlPlanning.DataBind();
                ddlPlanning_SelectedIndexChanged(this, EventArgs.Empty);

                if(currentPlanning != null)
                {
                    //Date selection
                    ddlPlanning.SelectedValue = currentPlanning.datum.ToString("dd-MM-yyyy");
                    ddlPlanning_SelectedIndexChanged(this, EventArgs.Empty);

                    //Time selection
                    rblTimes.SelectedValue = currentPlanning.tijd.ToString(@"hh\:mm");

                    //3D Glasses
                    if ((bool)currentPlanning.dried)
                    {
                        glassesTR.Visible = true;
                        glasses.Items.AddRange(Enumerable.Range(0, pm.getAvailableSeats(currentPlanning) + 1).Select(en => new ListItem(en.ToString())).ToArray());
                    }

                    //Make Buttons visible
                    if(pm.getAvailableSeats(currentPlanning) > 0)
                    {
                        buy.Visible = true;
                        if (mm.reservePosible(currentPlanning))
                        {
                            reserve.Visible = true;
                        }
                    }

                    //Repeater gets list of tickets
                    availableTickets.DataSource = tm.getAvailableTickets();
                    availableTickets.DataBind();
                    availableTickets.Visible = true;

                    //Get subscription for account
                    if (currentAccount.abbonement != null)
                    {
                        subscriptionName.Text = currentAccount.abbonement.abbonementnaam;
                        if (currentAccount.account_abbonement.aantal > 0)
                        {
                            subscription.Items.AddRange(Enumerable.Range(0, (int)currentAccount.account_abbonement.aantal + 1).Select(en => new ListItem(en.ToString())).ToArray());
                            subscriptionTR.Visible = true;
                        }
                        else if(currentAccount.account_abbonement.begindatum >= DateTime.Today.Date && currentAccount.account_abbonement.einddatum >= DateTime.Today.Date)
                        {
                            subscription.Items.AddRange(Enumerable.Range(1, 1).Select(en => new ListItem(en.ToString())).ToArray());
                            subscriptionTR.Visible = true;
                        }
                    }
                }

                //Repeater gets list of movie rated
                movieRatedRepeater.DataSource = currentMovie.kijkwijzers;
                movieRatedRepeater.DataBind();
            }
        }
        else
        {
            Response.Redirect("~/");
        }
    }

    protected void availableTickets_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        Label ticketName = (Label)e.Item.FindControl("ticketName");
        kaart_soort currentKaartSoort = (kaart_soort)e.Item.DataItem;
        
        String tempTicketName = (language.Equals("dutch") ? currentKaartSoort.kaart_soort_naam : currentKaartSoort.kaart_soort_naam_en);
        ticketName.Text = tempTicketName;

        DropDownList ticket = (DropDownList)e.Item.FindControl("ticket");
        ticket.Items.AddRange(Enumerable.Range(0, pm.getAvailableSeats(currentPlanning) + 1).Select(en => new ListItem(en.ToString())).ToArray());
    }

    public List<kaartje> getSelectedTickets()
    {
        List<kaartje> tickets = new List<kaartje>();

        foreach (ListViewItem listviewitem in availableTickets.Items)
        {
            DropDownList ticket = (DropDownList)listviewitem.FindControl("ticket");
            HiddenField ticketID = (HiddenField)listviewitem.FindControl("ticketID");

            int selectedAmount = int.Parse(ticket.SelectedValue);

            for (int i = 0; i < selectedAmount; i++)
            {
                kaartje tempKaartje = new kaartje();
                kaart_soort tempKaartSoort = tm.getTicket(int.Parse(ticketID.Value));
                tempKaartje.kaart_soort = tempKaartSoort;
                tempKaartje.planning_id = currentPlanning.planning_id;
                tickets.Add(tempKaartje);
            }
        }

        if (!subscription.SelectedValue.Equals(""))
        {
            int subscriptionAmount = int.Parse(subscription.SelectedValue);
            for (int i = 0; i < subscriptionAmount; i++)
            {
                kaartje tempKaartje = new kaartje();
                kaart_soort tempKaartSoort = tm.getTicket(1);
                tempKaartje.kaart_soort = tempKaartSoort;
                tempKaartje.planning_id = currentPlanning.planning_id;
                tempKaartje.abbonementabbonement_id = currentAccount.abbonementabbonement_id;
                tempKaartje.abbonement = currentAccount.abbonement;
                tickets.Add(tempKaartje);
            }
        }

        return tickets;
    }

    public void createOrder(String soort)
    {
        List<kaartje> chosenTickets = getSelectedTickets();
        if (chosenTickets.Count != 0)
        {
            if (chosenTickets.Count <= pm.getAvailableSeats(currentPlanning))
            {
                if ((chosenTickets.Count <= 10 && soort.Equals("reservering")) || soort.Equals("koop"))
                {
                    currentOrder = new bestelling();
                    currentOrder.active = true;
                    currentOrder.afgehaald = false;
                    currentOrder.betaald = false;
                    currentOrder.kaartjes = chosenTickets;
                    currentOrder.soort = soort;
                    currentOrder.tijd = DateTime.Now.TimeOfDay;
                    if ((bool)currentPlanning.dried)
                    {
                        currentOrder.brillen = int.Parse(glasses.SelectedValue);
                    }
                    currentOrder.planning = currentPlanning;
                    currentOrder.datum = DateTime.Today;
                    currentOrder.account = Master.getUser();
                    Session["order"] = currentOrder;
                    
                    if (currentPlanning.film.stoelen_kiezen == true)
                    {
                        if (Master.getUser() != null)
                        {
                            Response.Redirect("~/bestellen/stoelkeuze.aspx");
                        }
                        else
                        {
                            Response.Redirect("~/login.aspx?redirect=bestellen/stoelkeuze.aspx");
                        }
                    }
                    else
                    {
                        if (Master.getUser() != null)
                        {
                            Response.Redirect("~/bestellen/afrekenen.aspx");
                        }
                        else
                        {
                            Response.Redirect("~/login.aspx?redirect=bestellen/afrekenen.aspx");
                        }
                    }
                }
                else
                {
                    lblNotification.Text = "- " + Master.tl.getTranslation("ntfMax10") + ".";
                }
            }
            else
            {
                lblNotification.Text = "- " + Master.tl.getTranslation("ntfOnly") + " " + pm.getAvailableSeats(currentPlanning).ToString() + " " + Master.tl.getTranslation("ntfSeats") + ".";
            }
        }
        else
        {
            lblNotification.Text = "- " + Master.tl.getTranslation("ntfNoTickets") +".";
        }
    }

    protected void buy_Click(object sender, EventArgs e)
    {
        createOrder("koop");
    }

    protected void reserve_Click(object sender, EventArgs e)
    {
        createOrder("reservering");
    }

    protected void ddlPlanning_SelectedIndexChanged(object sender, EventArgs e)
    {
        availableTickets.Visible = false;
        buy.Visible = false;
        reserve.Visible = false;
        subscriptionTR.Visible = false;
        glassesTR.Visible = false;
        rblTimes.Items.Clear();
        DateTime chosenDate = DateTime.ParseExact(ddlPlanning.SelectedValue.ToString(),"d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
        DateTime currentDate = DateTime.Today.Date;

        List<planning> planningen = pm.getPlanningenMovieByDate(currentMovie.film_id, chosenDate, (chosenDate != currentDate ? false : true));
        if (planningen.Count > 0)
        {
            foreach (planning tempPlanning in planningen)
            {
                rblTimes.Items.Add(dtc.getTimeforMovie(tempPlanning.tijd));
            }
            noTimes.Visible = false;
        }
        else
        {
            noTimes.Visible = true;
        }
    }

    protected void rblTimes_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!rblTimes.SelectedValue.Equals(""))
        {
            currentPlanning = pm.getPlanningMovie(currentMovie.film_id, DateTime.Parse(ddlPlanning.SelectedValue.ToString()), TimeSpan.Parse(rblTimes.SelectedValue.ToString()));
            Session["Planning"] = currentPlanning;
            //Repeater gets list of tickets
            availableTickets.DataSource = tm.getAvailableTickets();
            availableTickets.DataBind();
            availableTickets.Visible = true;

            if ((bool)currentPlanning.dried)
            {
                glasses.Items.AddRange(Enumerable.Range(0, pm.getAvailableSeats(currentPlanning) + 1).Select(en => new ListItem(en.ToString())).ToArray());
                glassesTR.Visible = true;
            }
            else
            {
                glassesTR.Visible = false;
            }
            if (currentAccount.abbonement != null)
            {
                subscriptionTR.Visible = true;
            }

            //Make Buttons visible
            if (pm.getAvailableSeats(currentPlanning) > 0)
            {
                buy.Visible = true;
                if (mm.reservePosible(currentPlanning))
                {
                    reserve.Visible = true;
                }
                else
                {
                    reserve.Visible = false;
                }
            }
        }
        else
        {
            currentPlanning = null;
            Session["Planning"] = null;
            availableTickets.Visible = false;
            buy.Visible = false;
            reserve.Visible = false;
            glassesTR.Visible = false;
            subscriptionTR.Visible = false;
        }
    }
}